package com.scy.edu.server;

/**
 * @author 司晨雨
 * @date 2020/6/25 21:09
 * @description
 */

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号**/
    private int port = 8080;

    private MyMapper  myMapper = new MyMapper();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setMyMapper(MyMapper myMapper) {
        this.myMapper = myMapper;
    }

    public void setServletMap(Map<String, HttpServlet> servletMap) {
        this.servletMap = servletMap;
    }

    /**
     *Minicat启动初始化展开的操作
     */
    public void start() throws Exception {

        //loadServlet();

        loadServerXml();

        loadContext();

        //定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 100;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);






        /**
         完成Minicat 1.0版本
         需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=======>>>>Minicat start on port"+port);

        /*while (true){
            Socket socket = serverSocket.accept();
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/

        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.outputHtml(request.getUrl());
            socket.close();
        }*/

        /**
         * MiniCat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
       /*while(true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            //静态资源处理
            if(servletMap.get(request.getUrl()) == null){
                response.outputHtml(request.getUrl());
            }else{
                //动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }
            socket.close();
        }*/

        //多线程改造(不使用线程池)
       /* while(true){
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap,myMapper);
            requestProcessor.start();
        }*/

        while(true){
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap,myMapper);
            threadPoolExecutor.execute(requestProcessor);
        }




    }


    private Map<String,HttpServlet> servletMap = new HashMap<String, HttpServlet>();


    /**
     * 加载解析web.xml，初始化servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                //<servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                //<servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                //根据servlet-name的值找到url-pattren
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");

                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void loadServerXml(){
        InputStream stream = Bootstrap.class.getClassLoader().getResourceAsStream("server.xml");//初始化server.xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(stream);//读取server.xml
            Element rootElement = document.getRootElement();
            Node server = rootElement.selectSingleNode("//Server");
            List<Element> serviceList = server.selectNodes("//Service");
            for (int i = 0; i < serviceList.size(); i++) {
                Element serviceElement =  serviceList.get(i);
                List<Element> connectorList = serviceElement.selectNodes("Connector");
                for (int j = 0; j < connectorList.size(); j++) {
                    Element connectionElement = connectorList.get(j);
                    String port = connectionElement.attributeValue("port");
                    setPort(Integer.valueOf(port));
                    Node engineNode = connectionElement.selectSingleNode("Engine");
                    List<Element> hostList = engineNode.selectNodes("Host");
                    for (int k = 0; k < hostList.size(); k++) {
                        Element element =  hostList.get(k);
                        //获取host中name值与appbase值
                        String name = element.attributeValue("name");
                        String appBase = element.attributeValue("appBase");
                        //存放name值与appbase到myhost，存放到mymapper
                        MyHost myHost = new MyHost();
                        myHost.setName(name);
                        myHost.setAppBase(appBase);
                        myMapper.getHosts().add(myHost);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void loadContext() {

        List<MyHost> hosts = myMapper.getHosts();
        for (MyHost host:hosts) {
            String appBase = host.getAppBase();
            String name = host.getName();
            File ff = new File(appBase);
            if(ff.exists()){
                File[] fileList = ff.listFiles();
                for (File file : fileList) {
                    MyContext myContext=new MyContext();
                    if(file.isDirectory()){
                        myContext.setName(file.getName());
                        myContext.setContextPath(file.getAbsolutePath());
                        host.getMyContexts().add(myContext);
                    }
                }
            }
            List<MyContext> myContexts = host.getMyContexts();
            for (MyContext myContext : myContexts) {
                loadServlet(myContext);
            }
        }
    }

    private void loadServlet(MyContext myContext) {
        try {
            InputStream resourceAsStream = new FileInputStream(myContext.getWebXml());
            SAXReader reader = new SAXReader();
            Document document = reader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");

                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                MyClassLoader classLoader=new MyClassLoader();
                HttpServlet  o = (HttpServlet) classLoader.findClass(myContext.getContextPath(), servletClass).newInstance();
                HashMap<String, HttpServlet> map = new HashMap<String, HttpServlet>();
                map.put(urlPattern, o);
                MyWrapper myWrapper = new MyWrapper();
                myWrapper.setMapperServlet(map);
                myContext.getMyWrappers().add(myWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Minicat的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
